package orm

import (
	"bluebell_backend/models"
	"bluebell_backend/pkg/encrypt"
	"database/sql"
	"errors"
	"github.com/gin-gonic/gin"
)


type User struct {
	Id         int64          `gorm:"column:id;type:bigint(20);primary_key;AUTO_INCREMENT" json:"id"`
	UserId     int64          `gorm:"column:user_id;type:bigint(20);NOT NULL" json:"user_id"`
	Username   string         `gorm:"column:username;type:varchar(64);NOT NULL" json:"username"`
	Password   string         `gorm:"column:password;type:varchar(64);NOT NULL" json:"password"`
	Email      sql.NullString `gorm:"column:email;type:varchar(64)" json:"email"`
	Gender     int            `gorm:"column:gender;type:tinyint(4);default:0;NOT NULL" json:"gender"`
	CreateTime sql.NullTime   `gorm:"column:create_time;type:timestamp;default:CURRENT_TIMESTAMP" json:"create_time"`
	UpdateTime sql.NullTime   `gorm:"column:update_time;type:timestamp;default:CURRENT_TIMESTAMP" json:"update_time"`
}

func (this *User) TableName() string {
	return "user"
}


// gorm 方式查询数据库
func (this *User) GetLogin(ctx *gin.Context,userParams *models.User) (err error) {
	originPassword := userParams.Password // 记录一下原始密码(用户登录的密码)
	var userData User
	table := GetBlueBellDb().WithContext(ctx).Model(this)
	if userParams.UserName != " " {
		table.Where("username = ?", userParams.UserName)
	}
	// notice: first方法的入参必须是指针类型
	if result := table.First(&userData); result.Error != nil {
		return result.Error
	}
	// 生成加密密码与查询到的密码比较
	password := encrypt.EncryptPassword([]byte(originPassword))
	if userData.Password != password {
		return errors.New(ErrorPasswordWrong)
	}
	return nil
}
